package com.example.myapplication;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.media.AudioManager;
import android.os.Bundle;
import android.telecom.Call;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.w3c.dom.Text;

import java.util.Objects;
import java.util.prefs.Preferences;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout llo_outer;
    private SharedPreferences.Editor phoneBookEdit;
    private SharedPreferences.Editor cfgEdit;
    private View subLayout;
    private int name_size = 0;
    private int phone_size = 0;
    private SharedPreferences cfgPreferences;
    private SharedPreferences.Editor cfgEdit1;

    int name_max_count = 0;
    int phone_max_count = 0;

    TextView[] lloInners = null;
    int innersIndex = 0;
    int innersSize = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 存储所有的电话信息
        SharedPreferences preferences = getSharedPreferences("phones", MODE_PRIVATE);
        phoneBookEdit = preferences.edit();

        // 存储字体大小设置
        cfgPreferences = getSharedPreferences("config", MODE_PRIVATE);
        cfgEdit = cfgPreferences.edit();

        //        获取最外层的llo
        llo_outer = findViewById(R.id.llo_outer);
        innersSize = preferences.getAll().size() * 2;
        if (innersSize > 0) {
            lloInners = new TextView[innersSize];
        }

        for (String key : preferences.getAll().keySet()) {
            String value = preferences.getString(key, "默认电话号码");
            addsubView(key, value);
            if (!cfgPreferences.contains("name_size") && innersSize > 0) {
                name_max_count = updateMaxSize(key, name_max_count);
            }
            if (!cfgPreferences.contains("phone_size") && innersSize > 0) {
                phone_max_count = updateMaxSize(value, phone_max_count);
            }
        }
    }

    public int updateMaxSize(String str, int Max) {
        // 中文
        int count1 = 0;
        // 英文
        int count2 = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
                count1++;
            } else {
                count2++;
            }
        }
        return Math.max(Max, Math.round(count1 + (float) count2/2));
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
//        子视图完成后自动调用
        super.onWindowFocusChanged(hasFocus);

        if (hasFocus) {
            if (innersSize > 0) {
                int contentWidth = subLayout.getWidth() - subLayout.getPaddingLeft() - subLayout.getPaddingRight();
                float nameSize = 0;
                float phoneSize = 0;

                if (0 == name_max_count) {
                    nameSize = cfgPreferences.getFloat("name_size", 1206);
                } else {
                    nameSize = (float) contentWidth / name_max_count;
                    cfgEdit.putFloat("name_size", nameSize);
                }
                if (0 == phone_max_count) {
                    phoneSize = cfgPreferences.getFloat("phone_size", 1206);
                } else {
                    phoneSize = (float) contentWidth / phone_max_count;
                    cfgEdit.putFloat("phone_size", phoneSize);
                }

                for (int i = 0; i < innersSize; i++) {
                    if (i % 2 == 0) {
                        lloInners[i].setTextSize(TypedValue.COMPLEX_UNIT_PX, nameSize);
                    } else {
                        lloInners[i].setTextSize(TypedValue.COMPLEX_UNIT_PX, phoneSize);
                    }
                }
                cfgEdit.apply();
            }
        }
    }


    public void addsubView(String name_str, String phone_str) {

        // 加载子布局
        LayoutInflater inflater = LayoutInflater.from(this);
        subLayout = inflater.inflate(R.layout.inner_llo, null);
        // 将子布局添加到主布局
        llo_outer.addView(subLayout);

        TextView name = (TextView) ((LinearLayout) (((LinearLayout) subLayout).getChildAt(0))).getChildAt(0);
        TextView phone = (TextView) ((LinearLayout) (((LinearLayout) subLayout).getChildAt(0))).getChildAt(1);

        lloInners[innersIndex++] = name;
        lloInners[innersIndex++] = phone;
        name.setText(name_str);
        phone.setText(phone_str);
        subLayout.setOnClickListener(this);
    }

    private static final int CALL_PHONE_PERMISSION_REQUEST_CODE = 1;

    public void call(String phoneNumber) {

        if (!phoneNumber.isEmpty()) {
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                makeCall(phoneNumber);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        CALL_PHONE_PERMISSION_REQUEST_CODE);
            }
        } else {
            Toast.makeText(MainActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
        }
    }

    private void makeCall(String phoneNumber) {
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + phoneNumber));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            startActivity(callIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CALL_PHONE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                String phoneNumber = Objects.requireNonNull(getIntent().getStringExtra("phone")).trim();
                makeCall(phoneNumber);
            } else {
                Toast.makeText(this, "权限被拒绝，无法拨打电话", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioManager != null) {
            // 设置音频模式为通话模式
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            // 打开免提
            audioManager.setSpeakerphoneOn(true);
            // 获取语音通话的最大音量
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
            // 设置语音通话音量为最大
            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, maxVolume, 0);
        }
        String phone = ((TextView) ((LinearLayout) (((LinearLayout) v).getChildAt(0))).getChildAt(1)).getText().toString();
        call(phone);
    }
}
